package com.tzbank.wisdom.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tzbank.utils.CodeUtil;
import com.tzbank.utils.HttpUtil;
import com.tzbank.utils.ResultUtil;
import com.tzbank.wisdom.service.BusinessService;
import com.tzbank.wisdom.service.TellerService;
import com.tzbank.wisdom.utils.BusinessCodeUtil;
import com.tzbank.wisdom.utils.BusinessConstant;

import net.sf.json.JSONObject;

@Service(value = "tellerService")
public class TellerServiceImpl implements TellerService {
	
	final static String TELLERAPI = "http://api.vc.feihu365.com/vc/tran/";			//请求地址  ， 需要放配置文件
	
	@Autowired
    private BusinessService businessService;
    
	/**
     * 获取teller的交易数据
     * @param map
     * @return
     */
	public Map<String,Object> getTellerTrade(Map<String,String> map) {
		map.put("appKey", "tzb");
		String url = TELLERAPI + "query";
		String result =  HttpUtil.sendPost(url, JSONObject.fromObject(map).toString());
		return formatTellerData(result);
	}
	
	/**
     * 交易结果反馈给teller
     * @param map
     * @return
     */
	public String sendTellerResult(Map<String,String> map) {
		map.put("appKey", "tzb");
		map.put("tradeStatus", "success");
		String url = TELLERAPI + "result";
		return HttpUtil.sendPost(url, JSONObject.fromObject(map).toString());
	}
	
	/**
	 * 视频返回的数据分析
	 */
	private Map<String,Object> formatTellerData(String result) {
		//接口调用失败
		if(result == null) {
			return ResultUtil.resultMap(BusinessCodeUtil.CODE_30001.getName(), BusinessCodeUtil.CODE_30001.getCode(), null);
		}
		try {
			JSONObject resultJson =  JSONObject.fromObject(result);			//字符转对象
			String code = resultJson.getString("code");		//返回码
			//判断接口是否调用成功
			if(CodeUtil.CODE_200.getCode().equals(code)) {
				JSONObject dataBean = JSONObject.fromObject(resultJson.get("data")) ;		//将data数据转换成json对象
				dataBean.element("transferAmount", dataBean.getDouble("balance"));
				
				String businessType = dataBean.getString("businessType");		//获取业务类型
				if(BusinessConstant.BUSINESS_TYPE_TRANSFER.equals(businessType)) {
					//转账业务
					String themeId = "TA_001";			//转账主题id  这部分要看下如何获取
					dataBean.element("themeId", themeId);
			    	return businessService.getPageflow(dataBean);
				}else if(BusinessConstant.BUSINESS_TYPE_USER.equals(businessType)) {
					//用户变更   直接返回成功
					return ResultUtil.resultMap(CodeUtil.CODE_200.getName(), CodeUtil.CODE_200.getCode(), null);
				}
				return null;
			}else {
				return (Map<String,Object>) resultJson;			//转MAP返回
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.resultMap(BusinessCodeUtil.CODE_30001.getName(), BusinessCodeUtil.CODE_30001.getCode(), null);
		}
	}
}
